import { Viewer } from '@bytemd/react';
import styles from './index.less';
import gfm from '@bytemd/plugin-gfm';
import highlight from '@bytemd/plugin-highlight';//高亮代码块
import mediumZoom from '@bytemd/plugin-medium-zoom';// 缩放图片
import frontmatter from '@bytemd/plugin-frontmatter';// 解析前题
import breaks from '@bytemd/plugin-breaks';
// import 'juejin-markdown-themes/dist/condensed-night-purple.min.css' //网格背景
// import 'juejin-markdown-themes/dist/scrolls-light.min.css'
// import 'juejin-markdown-themes/dist/channing-cyan.min.css'
// import { getProcessor } from 'bytemd';
import { useState,useEffect } from 'react';
import { Anchor, Avatar, Drawer,Spin,message, } from 'antd';
import { UserOutlined } from '@ant-design/icons';
import Comment from './components/Comment';
import { useBoolean } from 'ahooks';
import FavoriteModal from './components/FavoriteModal';
import { getProcessor } from 'bytemd'//目录数据
import themePlugin from '../Editor/Themes';
import { useParams, useRequest } from '@umijs/max';
import { addLikeArticle, delLikeArticle, getArticleInfo, getCommentList, getUserDetailByUserId } from '@/services/article';
import { history } from '@umijs/max';
import { isMeById } from '@/utils/info';
import FollowButton from '@/components/FollowButton';
import SpinBox from '@/components/SpinBox';
import { useModel } from '@umijs/max';
import { useLazyList } from '@/hooks';



export default () => {
    const {setShowLogin,userInfo} = useModel('global')
    const [commentOpen,{toggle:toggleCommentOpen}] = useBoolean(false); //评论
    const [favoriteOpen,{toggle:toggleFavoriteOpen}] = useBoolean(false);//收藏
    const [numberObj,setNumberObj] = useState({
        "favorites": {
            count:0,
            flag:false,
        },
        "likes": {
            count:0,
            flag:false,
        },
    });
    const [commentLength,setCommentLength] = useState(0);
    const [menuData,setMenuData] = useState([]);
    const {id} = useParams();
    const plugins = [
        gfm(),
        highlight(),
        mediumZoom(),
        frontmatter(),
        breaks(),
        themePlugin(),
    ]
    // 获取文章节点内容,然后生成目录
    const createCataLog = () => {
       const res = [];
         const dom = document.querySelector('.markdown-body');
         if(!dom?.children) return
         let len = 0;
         Array.from(dom.children)?.forEach?.((item,index)=>{
            if(['H1','H2'].includes(item.tagName)){
                if(item.tagName==='H1'){
                    res.push({
                        key: `header-${len}`,
                        href: `#header-${len}`,
                        title: `${item.innerText}`,
                        children:[],
                    })
                }else{
                    (res.at(-1)?.children??res).push({
                        key: `header-${len}`,
                        href: `#header-${len}`,
                        title: `${item.innerText}`,
                    })
                }
                dom.children[index].setAttribute('id', `header-${len}`)//添加id
                len++;
            }
        })   
       setMenuData(res);
    }

    
    const {data:articleData={},loading} = useRequest(getArticleInfo,{
        defaultParams:[id],
        onSuccess:(res)=>{
            setNumberObj({
                "favorites":  {
                    count:res?.favorites,
                    flag:res?.isFavorite,
                },
                "likes": {
                    count:res?.likes,
                    flag:res?.isLike
                },
            })
            getAuthorDetail(res?.createdBy)
        }
    })
    useEffect(()=>{
        if(!loading){
            createCataLog()
        }
    },[loading])
    const {data:authorDetail,run:getAuthorDetail} = useRequest(getUserDetailByUserId,{
        manual:true,
    })
    const {run:opLike} = useRequest(numberObj.likes.flag?delLikeArticle:addLikeArticle,{
        manual:true,
        onSuccess:()=>{
            message.success(numberObj.likes.flag?'取消点赞成功':'点赞成功')
            setNumberObj((oldV)=>{
                oldV.likes.flag ? oldV.likes.count-- :oldV.likes.count++;
                oldV.likes.flag = !oldV.likes.flag;
                return oldV
            })
        }
    })

    const checkLogin = (fun) =>{
        if(!!userInfo?.id) return fun()
        setShowLogin(true)
    }
    const commentListInfo = useLazyList({ api: getCommentList, extraParams: { articleId: id } })

    useEffect(()=>{
        setCommentLength(commentListInfo?.pageParams.totalCount||0)
    },[commentListInfo?.pageParams?.totalCount])
    return <SpinBox loading={loading} size='large'>
        <div className={styles.container}>
    <div className={styles.fixedOp} >
        <div className={`${styles.opItem} ${numberObj.likes.flag&&styles.active}`} data-dz={numberObj.likes.count} onClick={()=>{
            checkLogin(()=>opLike(articleData.id))
        }}>
            <i className={`iconfont ${numberObj.likes.flag?'icon-a-Property1youbangzhuProperty2xuanzhong':'icon-a-Property1youbangzhuProperty2weixuanzhong'} ic`} />
        </div>
        <div className={styles.opItem} data-pl={commentLength}  onClick={()=>{toggleCommentOpen()}}>
            <i className='iconfont icon-comment ic' />
        </div>
        <div className={`${styles.opItem} ${numberObj.favorites.flag&&styles.active}`} data-sc={numberObj.favorites.count} onClick={()=>{
            checkLogin(()=>toggleFavoriteOpen())
            }}>
            <i className={`iconfont ${numberObj.favorites.flag?'icon-shoucang1':"icon-shoucang"} ic`} />
        </div>
    </div>
    <div className={styles.view}>
        <div className={styles.viewTop}>
            <h1 className={styles.title}>{articleData.title}</h1>
            <div className={styles.otherInfo}>
                <div className={styles.name} onClick={()=>{
                history.push(`/user/${articleData.createdBy}`)
            }}>{authorDetail?.nickname}</div>
                <div>{articleData.updatedTime}</div>
                <div><i className='iconfont icon-browse' />{articleData.views||0}</div>
                {
                    isMeById(articleData.createdBy)&&<div className={styles.edit} onClick={()=>{history.push(`/editor?articleId=${id}`)}}>编辑</div>
                }
            </div>
        </div>
        <Viewer value={articleData.content} plugins={plugins} />
    </div>
    <div className={styles.right}>
        <div className={styles.authorInfo}>
            <div className={styles.infoTop} onClick={()=>{
                history.push(`/user/${articleData.createdBy}`)
            }}>
                <Avatar size={48} icon={<UserOutlined />} src={authorDetail?.avatar} />
                <div className={styles.name}>
                    {authorDetail?.nickname}
                </div>
            </div>
            <div className={styles.infoMiddle}>
                <div className={styles.middleItem}><span>{authorDetail?.articleCount||0}</span><span>文章</span></div>
                <div className={styles.middleItem}><span>{authorDetail?.readCount||0}</span><span>阅读</span></div>
                <div className={styles.middleItem}><span>{authorDetail?.followCount||0}</span><span>粉丝</span></div>
            </div>
            <div className={styles.infoBottom}>
                <FollowButton onChange={()=>{
                    getAuthorDetail(articleData?.createdBy)
                }} userId={articleData.createdBy} isFollow={authorDetail?.isFollow} />
            </div>
        </div>  
        <Anchor
            affix={false}
            className={styles.menu}
            items={menuData}
            targetOffset={64}
            replace={true} /**点击锚点不记录历史。 */
        >
        </Anchor>
    </div>
    <Drawer  width={600} title="评论" open={commentOpen} onClose={()=>{toggleCommentOpen()}} >
        <Comment listProps={commentListInfo} onChange={(flag)=>{
            const len =flag ? (commentLength+1):(commentLength-1)
            setCommentLength(len)
        }} />
    </Drawer>
    <FavoriteModal open={favoriteOpen} onClose={()=>{toggleFavoriteOpen()}} id={'1'} onConfirm={(flag)=>{
        toggleFavoriteOpen()
        message.success(flag?'收藏成功':"取消收藏成功")
        const count = flag? (numberObj?.favorites.count+1):(numberObj?.favorites.count-1);
        setNumberObj({
            ...numberObj,
            "favorites":  {
                count:count,
                flag:flag,
            },
        })
    }}/>
</div>
    </SpinBox>
}